import store from "@/store";

/**
 * 封装路由方法 方便template中调用 $router.push(pageUrl)
 * @return {Promise}
 * */

export const router = {
  push(options) {
    if (typeof options === "string") {
      return uni.navigateTo({ url: options });
    }
    return uni.navigateTo(options);
  },
  replace(options) {
    if (typeof options === "string") {
      return uni.redirectTo({ url: options });
    }
    return uni.redirectTo(options);
  },
  back(delta = 1) {
    console.log(delta);
    return uni.navigateBack({ delta });
  },
};

/**
 * 是否为空值
 * */
export const isNull = (target) => {
  return target === "" || target === undefined || target === null;
};

/**
 * 提示框
 * @return {Promise} 显示结束后 返回resolve
 * */
export const toast = (title, icon = "none", mask = false) => {
  const duration = 2000;
  return new Promise((resolve) => {
    uni.showToast({
      title,
      icon,
      duration,
      mask,
    });
    setTimeout(resolve, duration);
  });
};

export const qs = {
  /**
   * json对象 转querystring 参数 基础版
   * @param {Object} obj 需要转换的对象
   * @return {String} 'a=1&b=2...'
   **/
  stringify(obj) {
    if (typeof obj === "string") {
      return obj;
    }
    let res = "";
    for (let key in obj) {
      let value = obj[key];
      value = value || "";
      res += `&${key}=${value}`;
    }
    return res.slice(1);
  },
  /**
   * querystring -> json 对象 基础版
   * @param {String} src
   * @return {Object} {a: 1, b: 2, ...}
   **/
  parse(src) {
    if (!src) return src;
    const arr = src.split("?");
    const getParam = (arr) => {
      let res = {};
      for (let item of arr) {
        let value = item.split("=")[1];
        value = value || "";
        res[item.split("=")[0]] = decodeURIComponent(value);
      }
      return res;
    };
    if (arr.length === 1) {
      return {};
    } else {
      return getParam(arr[1].split("&"));
    }
  },
};

/**
 * 获取用户系统信息
 * */
export const sys = () => {
  const info = uni.getSystemInfoSync();
  const navbarHeight = info.platform === "ios" ? 44 : 48;
  const headerHeight = info.statusBarHeight + navbarHeight;
  return { ...info, navbarHeight, headerHeight };
};

/**
 * 提示确认框
 * @return {Promise}
 * @param {String|Object} options showModal的参数 传入字符串时默认为content
 * */
export const modal = (options) => {
  return new Promise((resolve, reject) => {
    let params = {};
    if (typeof options === "string") {
      params.content = options;
    } else {
      params = JSON.parse(JSON.stringify(options));
    }
    uni.showModal({
      ...params,
      success(res) {
        if (res.confirm) {
          resolve();
        } else {
          reject();
        }
      },
    });
  });
};

export const getRawType = (val) => {
  /**
   * 获取对象数据类型
   * @param {any} val
   * @return {String} array string ...
   * */
  const toString = Object.prototype.toString;
  return toString.call(val).slice(8, -1).toLowerCase();
};

export const deepClone = (obj, map = new WeakMap()) => {
  /**
   *深拷贝对象(只考虑了普通的 object和 array两种数据类型)
   *@param {Object} obj 对象
   **/
  let type = getRawType(obj);
  if (type != "object" && type != "array") return obj;
  let clone = Array.isArray(obj) ? [] : {};
  if (map.get(obj)) {
    return obj;
  }
  map.set(obj, clone);
  for (let key in obj) {
    clone[key] = deepClone(obj[key], map);
  }
  return clone;
};

export const storage = {
  /**
   * 获取缓存
   * @param {String} key  key
   * @param {String} def  若想要无缓存时，返回默认值则get('key','默认值')
   */
  get(key, def = "") {
    // 获取缓存
    const timeout = parseInt(uni.getStorageSync(`${key}__separator__`) || 0);
    // 过期失效
    if (timeout) {
      if (Date.now() > timeout) {
        this.remove(key);
        return;
      }
    }
    let value = null;
    try {
      value = JSON.parse(uni.getStorageSync(key));
    } catch (err) {
      value = uni.getStorageSync(key);
    }
    return value || def;
  },
  set(key, value, timeout = 0) {
    /**
     * 设置缓存
     * @param {String} key       key
     * @param {Any} value     value
     * @param {Number} timeout   过期时间（单位：分钟）不设置时间即为永久保存
     */
    let _timeout = parseInt(timeout);
    let val = ["object", "array"].includes(getRawType(value)) ? JSON.stringify(value) : value;
    uni.setStorageSync(key, val);
    if (_timeout) {
      uni.setStorageSync(`${key}__separator__`, Date.now() + 1000 * 60 * _timeout);
    } else {
      uni.removeStorageSync(`${key}__separator__`);
    }
    return value;
  },
  remove(key) {
    // 移除缓存
    uni.removeStorageSync(key);
    uni.removeStorageSync(`${key}__separator__`);
    return undefined;
  },
};

export const interceptAliOssVideoFrame = (url, width = 0, height = 0) => {
  return url + "?x-oss-process=video/snapshot,t_1,f_jpg,w_" + width + ",h_" + height + ",m_fast";
};

export const jumpPage = (navUrl, type) => {
  switch (type) {
    case "url":
      uni.navigateTo({
        url: "/pages/webview/webview?src=" + encodeURIComponent(navUrl),
      });
      break;
    case "list":
      uni.navigateTo({ url: navUrl });
      break;
    case "article":
      uni.navigateTo({
        url: "/pages/webview/webview?src=" + encodeURIComponent(navUrl),
      });
      break;
    default:
      if (navUrl.indexOf("collect/index") != -1 || navUrl.indexOf("cloud-house/index") != -1) {
        if (!store.state.userInfo.isLogin) {
          uni.navigateTo({ url: "/pages/login/index" });
          return;
        }
      }
      uni.navigateTo({ url: navUrl });
      break;
  }
};

export const tsToDate = (ts) => {
  var bjdate = new Date(ts);
  return getFormatDate("yyyy-MM-dd hh:mm:ss", bjdate);
};

export const tsToCalendarDate = (ts) => {
  var bjdate = new Date(ts);
  return getFormatDate("yyyy年MM月dd日", bjdate);
};

function getFormatDate(fmt, date) {
  let opt = {
    "y+": date.getFullYear().toString(), // 年
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds(), //毫秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in opt) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? opt[k] : ("00" + opt[k]).substr(("" + opt[k]).length));
  return fmt;
}

export const fixPrice = (price) => {
  return (price / 100).toFixed(2);
};

